package com.itheima.controller;

import com.itheima.constant.JwtClaimsConstant;
import com.itheima.constant.MessageConstant;
import com.itheima.domain.dto.UserDTO;
import com.itheima.domain.entity.User;
import com.itheima.domain.vo.UserVO;
import com.itheima.properties.JwtProperties;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;
import com.itheima.utils.JwtUtil;
import com.itheima.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@Api(tags = "用户相关的接口")
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 用户登录
     * @param userDTO
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("用户登录")
    public Result login(@RequestBody UserDTO userDTO){
        log.info("userDTO:{}",userDTO);
        User user = userService.login(userDTO);
        if(user!=null){
            String password = userDTO.getPassword();
            if(password.equals(user.getPassword())){
                //登录成功后，生成jwt令牌
                Map<String, Object> claims = new HashMap<>();
                claims.put(JwtClaimsConstant.USER_ID, user.getId());
                String token = JwtUtil.createJWT(
                        jwtProperties.getSecretKey(),
                        jwtProperties.getTtl(),
                        claims);
                UserVO userVO = UserVO.builder()
                        .id(user.getId())
                        .username(user.getUsername())
                        .token(token)
                        .build();
                return Result.success(userVO);
            }
            return Result.error(MessageConstant.PASSWORD_ERROR);
        }
        return Result.error(MessageConstant.ACCOUNT_NOT_FOUND);
    }

    /**
     * 获取用户信息
     * @return
     */
    @GetMapping("/userInfo")
    @ApiOperation("获取用户信息")
    public Result<UserVO> userInfo() {
        UserVO userVo=userService.userInfo();
        return Result.success(userVo);
    }

    /**
     * 修改用户基本信息
     * @param userDTO
     * @return
     */
    @PutMapping("/update")
    public Result update(@RequestBody UserDTO userDTO) {
        log.info("userDTO:{}",userDTO);
        userService.update(userDTO);
        return Result.success();
    }
   
}
